package com.thales.sentinel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import com.thales.sentinel.model.LicenseException;
import com.thales.sentinel.model.LicenseInfo;
import com.thales.sentinel.service.LicenseValidationService;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Sentinel LDK Licensing REST Controller
 * 提供基于HTTP的API接口访问LDK许可功能
 */
@RestController
@RequestMapping("/api/license")
public class LdkLicensingController {

    private final LdkLicensingService ldkLicensingService;
    private final LicenseValidationService licenseValidationService;
    
    // 内存中的用户存储
    private final Map<Long, User> userStorage = new ConcurrentHashMap<>();
    private final AtomicLong userIdGenerator = new AtomicLong(1);

    @Autowired
    public LdkLicensingController(LdkLicensingService ldkLicensingService, 
                                 LicenseValidationService licenseValidationService) {
        this.ldkLicensingService = ldkLicensingService;
        this.licenseValidationService = licenseValidationService;
    }

    /**
     * 执行许可证操作
     * @param featureId 功能ID，默认为0
     * @return 操作结果
     */
    @GetMapping("/check")
    public String checkLicense(@RequestParam(value = "featureId", defaultValue = "0") int featureId) {
        return ldkLicensingService.performLicenseOperation(featureId);
    }

    /**
     * 健康检查接口
     * @return 服务状态信息
     */
    @GetMapping("/health")
    public String healthCheck() {
        return "Sentinel LDK Licensing Service is running!";
    }
    
    /**
     * 获取许可证信息接口
     * @return 许可证信息
     */
    @GetMapping("/info")
    public ResponseEntity<?> getLicenseInfo() {
        try {
            LicenseInfo licenseInfo = licenseValidationService.getCurrentLicenseInfo();
            return ResponseEntity.ok(licenseInfo);
        } catch (LicenseException e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(new ErrorResponse(e.getErrorType().name(), e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse("INTERNAL_ERROR", "获取许可证信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 验证许可证状态接口
     * @return 验证结果
     */
    @GetMapping("/validate")
    public ResponseEntity<?> validateLicense() {
        try {
            LicenseInfo licenseInfo = licenseValidationService.readLicenseFromHasp();
            licenseValidationService.validateLicenseExpiration(licenseInfo);
            
            Map<String, Object> result = new HashMap<>();
            result.put("valid", true);
            result.put("message", "许可证验证通过");
            result.put("expirationDate", licenseInfo.getExpirationDate());
            result.put("maxUsers", licenseInfo.getMaxUsers());
            result.put("currentUsers", userStorage.size());
            result.put("availableFeatures", licenseInfo.getRestrictions() != null ? 
                      licenseInfo.getRestrictions().getFeatureSet() : Collections.emptyList());
            
            return ResponseEntity.ok(result);
        } catch (LicenseException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("valid", false);
            result.put("error", e.getErrorType().name());
            result.put("message", e.getMessage());
            
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse("INTERNAL_ERROR", "许可证验证失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建用户demo接口
     * @param userRequest 用户创建请求
     * @return 创建的用户信息
     */
    @PostMapping("/users")
    public ResponseEntity<?> createUser(@RequestBody UserCreateRequest userRequest) {
        try {
            // 验证用户数量限制
            licenseValidationService.validateUserCount(userStorage.size());
            
            Long userId = userIdGenerator.getAndIncrement();
            User user = new User(userId, userRequest.getUsername(), userRequest.getEmail(), new Date());
            userStorage.put(userId, user);
            return ResponseEntity.ok(user);
        } catch (LicenseException e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(new ErrorResponse(e.getErrorType().name(), e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse("INTERNAL_ERROR", "创建用户失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取所有用户列表
     * @return 用户列表
     */
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return new ArrayList<>(userStorage.values());
    }
    
    /**
     * 根据ID获取用户
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/users/{userId}")
    public User getUserById(@PathVariable Long userId) {
        User user = userStorage.get(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + userId);
        }
        return user;
    }
    
    /**
     * 删除用户
     * @param userId 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/users/{userId}")
    public String deleteUser(@PathVariable Long userId) {
        User removedUser = userStorage.remove(userId);
        if (removedUser == null) {
            return "用户不存在: " + userId;
        }
        return "用户删除成功: " + removedUser.getUsername();
    }
    
    // 用户实体类
    public static class User {
        private Long id;
        private String username;
        private String email;
        private Date createdAt;
        
        public User() {}
        
        public User(Long id, String username, String email, Date createdAt) {
            this.id = id;
            this.username = username;
            this.email = email;
            this.createdAt = createdAt;
        }
        
        // Getters and Setters
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        
        public Date getCreatedAt() { return createdAt; }
        public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; }
    }
    
    // 用户创建请求类
    public static class UserCreateRequest {
        private String username;
        private String email;
        
        public UserCreateRequest() {}
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }
    
    // 错误响应类
    public static class ErrorResponse {
        private String errorType;
        private String message;
        private long timestamp;
        
        public ErrorResponse(String errorType, String message) {
            this.errorType = errorType;
            this.message = message;
            this.timestamp = System.currentTimeMillis();
        }
        
        public String getErrorType() { return errorType; }
        public void setErrorType(String errorType) { this.errorType = errorType; }
        
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        
        public long getTimestamp() { return timestamp; }
        public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
    }
}